package sy.controller.base;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.mapl.Mapl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import sy.model.base.JsonResult;
import sy.model.base.SessionInfo;
import sy.model.base.Tcompany;
import sy.model.base.Torganization;
import sy.model.base.Trole;
import sy.model.base.Tuser;
import sy.model.base.TuserTorganization;
import sy.model.base.TuserTrole;
import sy.service.base.CompanyServiceI;
import sy.service.base.OrganizationServiceI;
import sy.service.base.RoleServiceI;
import sy.service.base.UserOrganizationServiceI;
import sy.service.base.UserRoleServiceI;
import sy.service.base.UserServiceI;
import sy.util.base.BeanUtil;
import sy.util.base.ConfigUtil;
import sy.util.base.MD5Util;
import sy.util.base.QueryFilter;

/**
 * 
 * 不需要权限管理的控制器
 * 
 * @author 孙宇
 * 
 */
@Controller("guestController")
public class GuestController extends BaseController {

	@Resource(name = "userService")
	private UserServiceI userService;

	@Resource(name = "organizationService")
	private OrganizationServiceI organizationService;

	@Resource(name = "userOrganizationService")
	private UserOrganizationServiceI userOrganizationService;

	@Resource(name = "companyService")
	private CompanyServiceI companyService;

	@Resource(name = "roleService")
	private RoleServiceI roleService;

	@Resource(name = "userRoleService")
	private UserRoleServiceI userRoleService;

	/**
	 * 前台页面name="tuser."开头的，会自动封装到Tuser对象里面
	 * 
	 * @param binder
	 */
	@InitBinder("tuser")
	public void initBinderTuser(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("tuser.");
	}

	/**
	 * 默认访问index.jsp页面
	 * 
	 * @return
	 */
	@RequestMapping("/")
	public String index() {
		return "/login.jsp";
	}

	/**
	 * 获得所有公司
	 * 
	 * @param response
	 */
	@RequestMapping("/getCompanyAll")
	public void getCompanyAll(HttpServletResponse response, HttpServletRequest request) {
		QueryFilter filter = new QueryFilter(request);
		List<Tcompany> companys = companyService.findAll(filter);
		super.writeJson(response, companys);
	}

	/**
	 * 登录
	 * 
	 * @param response
	 */
	@RequestMapping("/login")
	public void login(HttpServletResponse response, HttpSession session, Tuser tuser) {
		JsonResult j = new JsonResult();
		QueryFilter filter = new QueryFilter();
		filter.addFilter("Q_t.name_EQ_S", tuser.getName());
		filter.addFilter("Q_t.pwd_EQ_S", MD5Util.md5(tuser.getPwd()));
		filter.addFilter("Q_t.tcompany.id_EQ_S", tuser.getTcompany().getId());
		Tuser u = userService.find(filter);
		if (u != null) {
			SessionInfo sessionInfo = new SessionInfo();
			sessionInfo.setUser(u);
			session.setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);
			j.setInfo("登陆成功！");
			j.setSuccess(true);
		} else {
			j.setInfo("登录名或密码错误！");
		}
		super.writeJson(response, j);
	}

	/**
	 * 初始化数据库
	 * 
	 * @return
	 */
	@RequestMapping("/init")
	public String init() {

		String json = Files.read("initDb.js");
		System.out.println(json);
		Object db = Json.fromJson(json);
		System.out.println(db);

		List companys = (List) Mapl.maplistToObj(Mapl.cell(db, "Tcompanys"), List.class);
		for (int i = 0; i < companys.size(); i++) {
			Tcompany company = (Tcompany) Mapl.maplistToObj(companys.get(i), Tcompany.class);
			Tcompany c = companyService.get(company.getId());
			if (c == null) {
				c = new Tcompany();
			}
			BeanUtil.copyNotNullProperties(company, c);
			companyService.saveOrUpdate(c);
		}

		List users = (List) Mapl.maplistToObj(Mapl.cell(db, "Tusers"), List.class);
		for (int i = 0; i < users.size(); i++) {
			Tuser user = (Tuser) Mapl.maplistToObj(users.get(i), Tuser.class);
			user.setPwd(MD5Util.md5(user.getPwd()));
			Tuser u = userService.get(user.getId());
			if (u == null) {
				u = new Tuser();
			}
			BeanUtil.copyNotNullProperties(user, u);
			userService.saveOrUpdate(u);
		}

		List organizations = (List) Mapl.maplistToObj(Mapl.cell(db, "Torganizations"), List.class);
		for (int i = 0; i < organizations.size(); i++) {
			Torganization organization = (Torganization) Mapl.maplistToObj(organizations.get(i), Torganization.class);
			Torganization o = organizationService.get(organization.getId());
			if (o == null) {
				o = new Torganization();
			}
			BeanUtil.copyNotNullProperties(organization, o);
			organizationService.saveOrUpdate(o);
		}

		List user_organizations = (List) Mapl.maplistToObj(Mapl.cell(db, "Tuser_Torganizations"), List.class);
		for (int i = 0; i < user_organizations.size(); i++) {
			String userId = (String) Mapl.cell(user_organizations.get(i), "userId");
			List organizationIds = (List) Mapl.maplistToObj(Mapl.cell(user_organizations.get(i), "organizationIds"), List.class);
			QueryFilter filter = new QueryFilter();
			filter.addFilter("Q_t.tuser.id_EQ_S", userId);
			List<TuserTorganization> uol = userOrganizationService.findAll(filter);
			for (TuserTorganization uo : uol) {
				userOrganizationService.delete(uo);
			}
			for (int k = 0; k < organizationIds.size(); k++) {
				Tuser tuser = new Tuser();
				tuser.setId(userId);
				Torganization torganization = new Torganization();
				torganization.setId((String) organizationIds.get(k));
				userOrganizationService.save(new TuserTorganization(UUID.randomUUID().toString(), torganization, tuser));
			}
		}

		List roles = (List) Mapl.maplistToObj(Mapl.cell(db, "Troles"), List.class);
		for (int i = 0; i < roles.size(); i++) {
			Trole role = (Trole) Mapl.maplistToObj(roles.get(i), Trole.class);
			Trole r = roleService.get(role.getId());
			if (r == null) {
				r = new Trole();
			}
			BeanUtil.copyNotNullProperties(role, r);
			roleService.saveOrUpdate(r);
		}

		List user_roles = (List) Mapl.maplistToObj(Mapl.cell(db, "Tuser_Troles"), List.class);
		for (int i = 0; i < user_roles.size(); i++) {
			String userId = (String) Mapl.cell(user_roles.get(i), "userId");
			List roleIds = (List) Mapl.maplistToObj(Mapl.cell(user_roles.get(i), "roleIds"), List.class);
			QueryFilter filter = new QueryFilter();
			filter.addFilter("Q_t.tuser.id_EQ_S", userId);
			List<TuserTrole> url = userRoleService.findAll(filter);
			for (TuserTrole ur : url) {
				userRoleService.delete(ur);
			}
			for (int k = 0; k < roleIds.size(); k++) {
				Tuser tuser = new Tuser();
				tuser.setId(userId);
				Trole trole = new Trole();
				trole.setId((String) roleIds.get(k));
				userRoleService.save(new TuserTrole(UUID.randomUUID().toString(), trole, tuser));
			}
		}

		return "/login.jsp";
	}

}
